package com.ruoyi.consumer.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.consumer.domain.CCar;
import com.ruoyi.consumer.domain.CCompany;
import com.ruoyi.consumer.domain.CUser;
import com.ruoyi.consumer.domain.CompanyBind;
import com.ruoyi.consumer.service.impl.CCarServiceImpl;
import com.ruoyi.consumer.service.impl.CCompanyServiceImpl;
import com.ruoyi.consumer.service.impl.CUserServiceImpl;
import com.ruoyi.consumer.service.impl.CompanyBindServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author: lizhouwei
 * @ date : 2023/10/24
 * @description:
 */
@Api(tags = "车队长相关操作")
@RestController
@RequestMapping("/api/captain")
public class CaptainController {

    @Autowired
    private CCarServiceImpl carService;

    @Autowired
    private CUserServiceImpl userService;

    @Autowired
    private CCompanyServiceImpl companyService;

    @Autowired
    private CompanyBindServiceImpl bindService;

    @Autowired
    private RedisCache redisCache;


    /**
     * 车队长绑定司机到手下
     */
    @ApiOperation("车队长绑定司机到手下")
    @PostMapping("/bind-driver-to-leader")
    public AjaxResult bindDriverToLeader(@ApiParam(value = "被绑定用户id", required = true) Integer userId, @ApiParam(value = "车队长id", required = true) Integer leaderId) {

        Assert.notNull(userId, "被绑定用户id不能为空");
        Assert.notNull(leaderId, "车队长id不能为空");

        //查询用户信息
        CUser cUser = userService.selectCUserByUserId(userId);
        Assert.notNull(cUser, "用户不存在");
        //查询车队长信息
        CUser leader = userService.selectCUserByUserId(leaderId);
        Assert.notNull(leader, "车队长不存在");
        if (userId == leaderId) {
            return AjaxResult.error("不能绑定自己");
        }
        Assert.isTrue(leader.getUserRole() == 1, "该用户不是车队长");
        //先删掉之前初始的绑定司机因为现在该用户是车队长
        CompanyBind firstBind = new CompanyBind();
        firstBind.setConsumerId(leaderId);
        List<CompanyBind> companyBinds = bindService.selectCompanyBindList(firstBind);
        if (companyBinds.size() > 0) {
            companyBinds.forEach(companyBind -> {
                bindService.deleteCompanyBindByBindId(companyBind.getBindId());
            });
        }

        //查询公司信息
        CCompany cCompany = companyService.selectCCompanyByCompanyId(leader.getCompanyId());
        System.out.println(cCompany);
        System.out.println(leader.getCompanyId());
        Assert.notNull(cCompany, "公司不存在");

        //绑定员工
        CompanyBind companyBind = new CompanyBind();
        companyBind.setCompanyId(leader.getCompanyId());
        companyBind.setConsumerId(cUser.getUserId());
        List<CompanyBind> bind = bindService.selectCompanyBindList(companyBind);

        if (bind.isEmpty()) {
            return AjaxResult.error("该用户不是本公司成员");
        } else {

            CompanyBind company_Bind = bind.get(0);

            if (!Objects.equals(company_Bind.getCompanyId(), leader.getCompanyId())) {
                return AjaxResult.error("该用户已经绑定其他公司");
            }
            if (company_Bind.getSysUserId() == (leader.getUserId()).longValue()) {
                return AjaxResult.error("该用户已经是本车队成员");
            }
            if (company_Bind.getSysUserId() != 0 && company_Bind.getSysUserId() != (leader.getUserId()).longValue()) {
                return AjaxResult.error("该用户已经绑定其他车队");
            }
        }

        companyBind.setBindId(bind.get(0).getBindId());
        companyBind.setDeptId(Long.valueOf(cCompany.getCompanDept()));
        companyBind.setSysUserId(Long.valueOf(leader.getUserId()));
        bindService.updateCompanyBind(companyBind);
        return AjaxResult.success("绑定成功");
    }


    /**
     * 查看自己车队成员
     *
     * @param userId
     * @return
     */
    @ApiOperation("查看自己车队成员")
    @GetMapping("/getMyTeam")
    public AjaxResult getMyTeam(@ApiParam(value = "车队长id", required = true) Integer userId) {
        Assert.notNull(userId, "车队长id不能为空");
        //查询车队长信息
        CUser leader = userService.selectCUserByUserId(userId);
        Assert.notNull(leader, "车队长不存在");

        //查询绑定信息
        CompanyBind companyBind = new CompanyBind();
        companyBind.setCompanyId(leader.getCompanyId());
        companyBind.setSysUserId(Long.valueOf(leader.getUserId()));
        List<CompanyBind> companyBinds = bindService.selectCompanyBindList(companyBind);
        if (companyBinds.isEmpty()) {
            return AjaxResult.success("暂无成员", null);
        }

        List<AjaxResult> cUsers = new ArrayList<>();
        //查询成员信息
        for (CompanyBind bind : companyBinds) {
            CUser cUser = userService.selectCUserByUserId(bind.getConsumerId());
            if (cUser == null) {
                continue;
            }
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("userId", cUser.getUserId());
            ajaxResult.put("userPhone", cUser.getUserPhone());
            ajaxResult.put("userNick", cUser.getUserNick());
            ajaxResult.put("userHeader", cUser.getUserHeader());
            ajaxResult.put("userName", cUser.getUserName());
            ajaxResult.put("userRole", cUser.getUserRole());
            ajaxResult.put("userStatus", cUser.getCarId() == 0 ? "空闲" : "有车");
            cUsers.add(ajaxResult);
        }
        return AjaxResult.success("success", cUsers);
    }

    /**
     * 查询车队长手下空闲的司机
     */
    @ApiOperation("查询车队长手下空闲的司机")
    @GetMapping("/getFreeDriver")
    public AjaxResult getFreeDriver(@ApiParam(value = "车队长id", required = true) Integer userId) {
        Assert.notNull(userId, "车队长id不能为空");
        //查询车队长信息
        CUser leader = userService.selectCUserByUserId(userId);
        Assert.notNull(leader, "车队长不存在");

        //查询绑定信息
        CompanyBind companyBind = new CompanyBind();
        companyBind.setCompanyId(leader.getCompanyId());
        companyBind.setSysUserId(Long.valueOf(leader.getUserId()));
        List<CompanyBind> companyBinds = bindService.selectCompanyBindList(companyBind);
        if (companyBinds.isEmpty()) {
            return AjaxResult.success("暂无成员", null);
        }

        List<AjaxResult> cUsers = new ArrayList<>();
        //查询成员信息
        for (CompanyBind bind : companyBinds) {
            CUser cUser = userService.selectCUserByUserId(bind.getConsumerId());
            if (cUser == null) {
                continue;
            }
            if (cUser.getCarId() != 0) {
                continue;
            }
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("userId", cUser.getUserId());
            ajaxResult.put("userPhone", cUser.getUserPhone());
            ajaxResult.put("userNick", cUser.getUserNick());
            ajaxResult.put("userHeader", cUser.getUserHeader());
            ajaxResult.put("userName", cUser.getUserName());
            ajaxResult.put("userRole", cUser.getUserRole());
            ajaxResult.put("userStatus", cUser.getCarId() == 0 ? "空闲" : "有车");
            cUsers.add(ajaxResult);
        }
        return AjaxResult.success("success", cUsers);
    }


    /**
     * 解绑员工
     *
     * @param leaderId
     * @param userId
     * @return
     */
    @ApiOperation("解绑员工")
    @PostMapping("/unbindStaff")
    public AjaxResult unbindStaff(@ApiParam(value = "车队长id", required = true) Integer leaderId, @ApiParam(value = "被解绑用户id", required = true) Integer userId) {
        Assert.notNull(userId, "用户id不能为空");
        //查询用户信息
        CUser cUser = userService.selectCUserByUserId(userId);
        if (cUser == null) {
            return AjaxResult.error("用户不存在");
        }
        if (cUser.getCompanyId() == 0) {
            return AjaxResult.error("用户未绑定公司");
        }

        //解绑员工
        //查询绑定
        CompanyBind companyBind = new CompanyBind();
        companyBind.setSysUserId(Long.valueOf(leaderId));
        companyBind.setConsumerId(userId);
        List<CompanyBind> companyBinds = bindService.selectCompanyBindList(companyBind);
        if (companyBinds.isEmpty()) {
            return AjaxResult.error("用户未绑定公司");
        }
        CompanyBind bind = companyBinds.get(0);
        bind.setSysUserId(0L);
        int i = bindService.updateCompanyBind(bind);
        Assert.isTrue(i > 0, "解绑失败");

        return AjaxResult.success("解绑成功");
    }

    //用户主动解绑公司
    @ApiOperation("用户主动解绑公司")
    @PostMapping("/user-unbind-company")
    AjaxResult unbindStaffCompany(@ApiParam(value = "申请解绑用户id", required = true) Integer userId) {
        Assert.notNull(userId, "用户id不能为空");
        //查询用户信息
        CUser cUser = userService.selectCUserByUserId(userId);
        if (cUser == null) {
            return AjaxResult.error("用户不存在");
        }
        if (cUser.getCompanyId() == 0) {
            return AjaxResult.error("用户未绑定公司");
        }
        if (cUser.getUserRole() == 1) {
            return AjaxResult.error("车队长不能解绑公司");
        }
        if (cUser.getCarId() != 0) {
            return AjaxResult.error("司机还有绑定车辆，不能解绑公司，请先联系车队长解绑车辆");
        }
        //解绑员工
        //更新用户信息
        cUser.setCompanyId(0);
        int i1 = userService.updateCUser(cUser);
        //查询绑定
        CompanyBind companyBind = new CompanyBind();
        companyBind.setConsumerId(userId);
        List<CompanyBind> companyBinds = bindService.selectCompanyBindList(companyBind);
        if (companyBinds.isEmpty()) {
            return AjaxResult.error("用户未绑定公司");
        }
        bindService.deleteCompanyBindByBindId(companyBinds.get(0).getBindId());
        redisCache.deleteObject("companyInfo:" + userId);
        return AjaxResult.success("解绑成功");
    }

    //车队经理主动解绑公司并转让关系
    @ApiOperation("车队经理主动解绑公司并转让关系")
    @PostMapping("/leader-unbind-company")
    AjaxResult unbindLeaderCompany(@ApiParam(value = "申请解绑用户id", required = true) Integer userId,
                                   @ApiParam(value = "被指定车队经理id", required = true) Integer leaderId) {
        Assert.notNull(userId, "用户id不能为空");
        //查询用户信息
        CUser cUser = userService.selectCUserByUserId(userId);
        CUser User = userService.selectCUserByUserId(leaderId);
        if (cUser == null || User == null) {
            return AjaxResult.error("用户不存在");
        }
        if (userId == leaderId) {
            return AjaxResult.error("无法转让给自己");
        }
        if (cUser.getCompanyId() == 0) {
            return AjaxResult.error("用户未绑定公司");
        }
        if (cUser.getUserRole() != 2) {
            return AjaxResult.error("该用户不是车队经理");
        }
        if (User.getCompanyId() == null || User.getCompanyId() == 0) {
            return AjaxResult.error("指定用户未绑定公司");
        }
        if (cUser.getCompanyId() != User.getCompanyId()) {
            return AjaxResult.error("指定户不是本公司成员");
        }

        //解绑员工
        //        //如果经理本人同时为车队长的情况
        CompanyBind bind1 = new CompanyBind();
        bind1.setMangerId(userId);
        bind1.setSysUserId(Long.valueOf(userId));
        bind1.setCompanyId(cUser.getCompanyId());
        List<CompanyBind> binds = bindService.selectCompanyBindList(bind1);
        if (!binds.isEmpty()) {
            //查找车辆
            CCar cCar = new CCar();
            cCar.setCarLeaderId(userId);
            List<CCar> cCars = carService.selectCCarList(cCar);
            if (!cCars.isEmpty()) {
                return AjaxResult.error("本人同时为车队长请先解绑本人绑定车辆");
            } else {
                for (CompanyBind bind : binds) {
                    bindService.deleteCompanyBindByBindId(bind.getBindId());
                }
            }
        }

//        查询车队经理手下的车辆
        CCar cCar = new CCar();
        cCar.setManagerId(userId);
        List<CCar> cCars = carService.selectCCarList(cCar);
        if (!cCars.isEmpty()) {
            for (CCar car : cCars) {
                car.setManagerId(leaderId);
                carService.updateCCar(car);
            }
        }
        CompanyBind companyBind = new CompanyBind();
        companyBind.setMangerId(userId);
        companyBind.setCompanyId(cUser.getCompanyId());
        List<CompanyBind> companyBinds = bindService.selectCompanyBindList(companyBind);
        if (companyBinds.isEmpty()) {
            return AjaxResult.error("指定用户已是属于他车队经理管理,请指定自己的手下");
        }
        for (CompanyBind bind : companyBinds) {
            CompanyBind company_Bind = new CompanyBind();
            company_Bind.setBindId(bind.getBindId());
            company_Bind.setMangerId(leaderId);
            //更新绑定信息，异常处理
            int i = bindService.updateCompanyBind(company_Bind);
            cUser.setCompanyId(0);
            cUser.setUserRole(0);
            cUser.setCarId(0);
            int i1 = userService.updateCUser(cUser);
            User.setUserRole(2);
            int i2 = userService.updateCUser(User);
            if (i <= 0) {
                return AjaxResult.error("转让失败");
            }
        }
        redisCache.deleteObject("companyInfo:" + userId);
        return AjaxResult.success("转让成功");
    }

    //车队经理主动解绑公司并保留关系
    @ApiOperation("车队经理主动解绑公司并保留关系")
    @PostMapping("/leader-unbind-company-keep")
    AjaxResult unbindLeaderCompanyKeep(@ApiParam(value = "申请解绑用户id", required = true) Integer userId) {
        Assert.notNull(userId, "用户id不能为空");
        //查询用户信息
        CUser cUser = userService.selectCUserByUserId(userId);
        if (cUser == null) {
            return AjaxResult.error("用户不存在");
        }
        if (cUser.getCompanyId() == 0) {
            return AjaxResult.error("用户未绑定公司");
        }
        if (cUser.getUserRole() != 2) {
            return AjaxResult.error("该用户不是车队经理");
        }

        //解绑员工
        //查询绑定
        CompanyBind bind1 = new CompanyBind();
        bind1.setMangerId(userId);
        bind1.setSysUserId(Long.valueOf(userId));
        bind1.setCompanyId(cUser.getCompanyId());
        List<CompanyBind> binds = bindService.selectCompanyBindList(bind1);
        if (!binds.isEmpty()) {
            //查找车辆
            CCar cCar = new CCar();
            cCar.setCarLeaderId(userId);
            List<CCar> cCars = carService.selectCCarList(cCar);
            if (!cCars.isEmpty()) {
                return AjaxResult.error("本人同时为车队长请先解绑本人绑定车辆");
            }
        }
        //更新用户信息
        cUser.setCompanyId(0);
        cUser.setUserRole(0);
        cUser.setCarId(0);
        int i1 = userService.updateCUser(cUser);
        //将退公司的经理id存入redis
        redisCache.setCacheObject("unbindLeader:" + userId, userId);
        redisCache.deleteObject("companyInfo:" + userId);
        return AjaxResult.success("退出成功");
    }

    //后台查询保留关系的车队经理
    @ApiOperation("后台查询保留关系的车队经理")
    @GetMapping("/get-keep-leader")
    public AjaxResult getKeepLeader() {
        // 获取所有匹配的键名
        Set<String> keys = (Set<String>) redisCache.keys("unbindLeader:*");
        System.out.println("keys打印出所有的键名:" + keys); // 打印出所有的键名
        List<Object> list = new ArrayList<>();
        // 遍历并取出每个键的值
        for (String key : keys) {
            Object value = redisCache.getCacheObject(key);
            System.out.println(value); // 打印出每个键对应的值
            CUser cUser = userService.selectCUserByUserId((Integer) value);
            list.add(cUser);
        }
        return AjaxResult.success("查询成功", list);
    }

}


